<?php
if (!defined('ROOT'))
{
    define('ROOT', '../');
}
class ItemManager
{
    var $template_parser = null;
    var $modx = null;
    var $modx_base_path = null;
    var $modx_base_url = null;
    var $page = null;
    var $url = null;
    var $show_debug = null;
    var $data = null;
    var $root_id = -1;
    var $page_id = -1;
    var $template = null;

    var $roomset_id = -1;
    var $collection_id = -1;
    var $furniture_type_id = -1;

    function ItemManager(&$template_parser, &$modx)
    {
        $this->template_parser = &$template_parser;
        $this->modx = &$modx;
        $this->modx_base_path = MODX_BASE_PATH;
        $this->modx_base_url = MODX_BASE_URL;
        $this->template_parser->content['modx_base_path'] = MODX_BASE_PATH;
        $this->template_parser->content['modx_base_url'] = MODX_BASE_URL;

        if ($this->template_parser->content['create_database'])
        {
            $this->modx->db->query("DROP TABLE IF EXISTS `modx_item_manager_categories`;");
            $this->modx->db->query("CREATE TABLE IF NOT EXISTS `modx_item_manager_categories` (
                                      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                                      `name` varchar(60) NOT NULL,
                                      `title` varchar(60),
                                      `description` text(0),
                                      `position` int(11) DEFAULT '-1',
                                      `created` datetime,
                                      `modified` datetime,
                                      `parent_id` int(11) DEFAULT '0',
                                      `permalink` varchar(60),
                                      PRIMARY KEY(`id`)
                                    )
                                    ENGINE=MYISAM
                                    ROW_FORMAT=default
                                    CHARACTER SET utf8
                                    COLLATE utf8_general_ci ;");

            $this->modx->db->query("DROP TABLE IF EXISTS `modx_item_manager_categories_items`;");
            $this->modx->db->query("CREATE TABLE IF NOT EXISTS `modx_item_manager_categories_items` (
                                      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                                      `category_id` int(11),
                                      `item_id` int(11),
                                      PRIMARY KEY(`id`)
                                    )
                                    ENGINE=MYISAM
                                    ROW_FORMAT=default
                                    CHARACTER SET utf8
                                    COLLATE utf8_general_ci ;");

            $this->modx->db->query("DROP TABLE IF EXISTS `modx_item_manager_items`;");
            $this->modx->db->query("CREATE TABLE IF NOT EXISTS `modx_item_manager_items` (
                                      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                                      `name` varchar(60) NOT NULL,
                                      `code` varchar(60),
                                      `price` varchar(60),
                                      `description` text(0),
                                      `size` varchar(60),
                                      `text_01` varchar(60),
                                      `text_02` varchar(60),
                                      `text_03` varchar(60),
                                      `hits` int(11) DEFAULT '0',
                                      `position` int(11) DEFAULT '-1',
                                      `created` datetime,
                                      `modified` datetime,
                                      `permalink` varchar(60),
                                      PRIMARY KEY(`id`)
                                    )
                                    ENGINE=MYISAM
                                    ROW_FORMAT=default
                                    CHARACTER SET utf8
                                    COLLATE utf8_general_ci ;");

            $this->modx->db->query("DROP TABLE IF EXISTS `modx_item_manager_files`;");
            $this->modx->db->query("CREATE TABLE `modx_item_manager_files` (
                                      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                                      `file_name` varchar(255) NOT NULL,
                                      `file_size` int(11),
                                      `mime_type` varchar(50),
                                      `type` enum('category','item'),
                                      `owner_id` int(11),
                                      `is_primary` tinyint(1) DEFAULT '0',
                                      PRIMARY KEY(`id`)
                                    )
                                    ENGINE=MYISAM
                                    ROW_FORMAT=default
                                    CHARACTER SET utf8
                                    COLLATE utf8_general_ci ;");
            }
    }

    function set($var_name, $value)
    {
        $this->template_parser->content[$var_name] = $value;
    }

    function append($var_name, $value)
    {
        $this->template_parser->content[$var_name] .= $value;
    }

    function get($var_name)
    {
        return $this->template_parser->content[$var_name];
    }

    function checkAccess()
    {
        if (empty($_SESSION['login']['username']))
        {
            $username = $this->modx->db->escape($_POST['username']); // this should have been done with the POST
            $password = $this->modx->db->escape($_POST['password']); // values before passing them to the function

            $res = $this->modx->db->select("id", $this->modx->getFullTableName('web_users'), "username='" . $username . "' AND password='" . md5($password) . "'");
            if ($this->modx->db->getRecordCount($res))
            {
                $id = $this->modx->db->getValue($res);
                $_SESSION['login']['user_id'] = $id;
                $_SESSION['login']['username'] = $username;
            }
            else
            {
                //incorrect login
            }
        }
    }

    function debug($var = false, $showHtml = false, $showFrom = true)
    {
        if ($this->show_debug)
        {
            if ($showFrom)
            {
                $calledFrom = debug_backtrace();
                $this->template_parser->content['debug.info'] .= '<strong>' . substr(str_replace(ROOT, '', $calledFrom[0]['file']), 1) . '</strong>';
                $this->template_parser->content['debug.info'] .= ' (line <strong>' . $calledFrom[0]['line'] . '</strong>)';
            }
            $this->template_parser->content['debug.info'] .= "\n<pre>\n";

            $var = print_r($var, true);
            if ($showHtml)
            {
                $var = str_replace('<', '&lt;', str_replace('>', '&gt;', $var));
            }
            $this->template_parser->content['debug.info'] .= $var . "\n</pre>\n";
        }
    }

    // Generate a random character string
    function generateRandomString($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
    {
        // Length of character list
        $chars_length = (strlen($chars) - 1);

        // Start our string
        $string = $chars{rand(0, $chars_length)};

        // Generate random string
        for ($i = 1; $i < $length; $i = strlen($string))
        {
            // Grab a random character from our list
            $r = $chars{rand(0, $chars_length)};

            // Make sure the same two characters don't appear next to each other
            if ($r != $string{$i - 1})
                $string .= $r;
        }

        // Return the string
        return $string;
    }

    function showMessage($message, $id = 'none')
    {
        $this->template_parser->content['view.message'] = '<div id="' . $id . '">';
        if (is_array($message))
        {
            foreach ($message as $msg)
            {
                $this->template_parser->content['view.message'] .= $msg . '<br />';
            }
        }
        elseif (is_string($message))
        {
            $this->template_parser->content['view.message'] .= $message;
        }
        $this->template_parser->content['view.message'] .= '</div>';
    }

    function genereateBreadcrumb()
    {
        $root_id = empty($_REQUEST['root_id']) ? 0 : $_REQUEST['root_id'];
        $type = empty($_REQUEST['type']) ? 'cat' : $_REQUEST['type'];

        if (!empty($root_id) && is_numeric($root_id) && $root_id > 0)
        {
            $arrow = "<img src=\"{$this->modx_base_url}assets/modules/item_manager/images/li.gif\" alt=\"arrow\" />";
            $this->template_parser->content['breadcrumb'] .= "<p class=\"gallery-breadcrumb\">Go back to: <a href=\"index.php?id={$this->page_id}\">Gallery</a>";

            $parent = $this->getCategoryParent($root_id);
            $parent_size = sizeof($parent);

            for ($i = $parent_size - 1; $i >= 0; $i--)
            {
                if ($parent[$i]['id'] == $this->root_id)
                {
                    continue;
                }

                if ($i == 0)
                {

                    if ($type == 'view_album')
                    {
                        $this->template_parser->content['breadcrumb'] .= " $arrow <a href=\"index.php?id={$this->page_id}&root_id={$parent[$i]['id']}&type=img\">{$parent[$i]['name']}</a>";
                    }
                    else
                    {
                        $this->template_parser->content['breadcrumb'] .= " $arrow {$parent[$i]['name']}";
                    }

                }
                else
                {
                    $this->template_parser->content['breadcrumb'] .= " $arrow <a href=\"index.php?id={$this->page_id}&root_id={$parent[$i]['id']}&type=cat\">{$parent[$i]['name']}</a>";
                }
            }

            $this->template_parser->content['breadcrumb'] .= "</p>";
        }
    }

    function genereateRanaBreadcrumb()
    {
        $root_id = empty($_REQUEST['pcat']) ? -1 : $_REQUEST['pcat'];

        if (!empty($root_id) && is_numeric($root_id) && $root_id > 0)
        {
            $arrow = "<img src=\"{$this->modx_base_url}assets/modules/item_manager/images/li.gif\" alt=\"arrow\" />";
            $this->template_parser->content['breadcrumb'] .= "<p class=\"pb5\">Back to:";

            $parent = $this->getCategoryParent($root_id);
            $parent_size = sizeof($parent);

            $parent_start = $parent_size - $parent_size;
            for ($i = $parent_start; $i >= 0; $i--)
            {
                if ($i == $parent_start)
                {
                    $arrow = '';
                }
                else
                {
                    $arrow = "<img src=\"{$this->modx_base_url}assets/modules/item_manager/images/li.gif\" alt=\"arrow\" />";
                }
                $this->template_parser->content['breadcrumb'] .= " $arrow <a href=\"{$this->template_parser->content['current_pagination_url']}\">{$parent[$i]['name']}</a>";
            }

            $this->template_parser->content['breadcrumb'] .= "</p>";
        }
    }

    function getCategoryParent($category_id, &$parent = array())
    {
        if (empty($category_id) || !is_numeric($category_id))
        {
            $category_id = 0;
        }

        $table_name = $this->modx->getFullTableName('item_manager_categories');
        $query_category = "SELECT * FROM $table_name WHERE id = $category_id";
        $result_category = $this->modx->db->query($query_category);

        while ($category_row = $this->modx->db->getRow($result_category))
        {
            $parent[] = $category_row;

            if (!empty($category_row['parent_id']))
            {
                $this->getCategoryParent($category_row['parent_id'], $parent);
            }
        }

        return $parent;
    }

    function createPermalink($str, $seperator = '-')
    {
        if (strlen($str) == 0) return $str;
        $str = preg_replace('/á|à|ả|ã|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/','a',$str);
        $str = preg_replace('/Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ/','A',$str);
        $str = preg_replace('/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ễ|ệ/','e',$str);
        $str = preg_replace('/É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ/','E',$str);
        $str = preg_replace('/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/','u',$str);
        $str = preg_replace('/Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự/','U',$str);
        $str = preg_replace('/ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ/','o',$str);
        $str = preg_replace('/Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ/','O',$str);
        $str = preg_replace('/í|ì|ỉ|ĩ|ị/','i',$str);
        $str = preg_replace('/Í|Ì|Ỉ|Ĩ|Ị/','I',$str);
        $str = preg_replace('/ý|ỳ|ỷ|ỹ|ỵ/','y',$str);
        $str = preg_replace('/Ý|Ỳ|Ỷ|Ỹ|Ỵ/','Y',$str);
        $str = preg_replace('/đ/','d',$str);
        $str = preg_replace('/Đ/','D',$str);
        $str = strtolower($str);
        if ($seperator)
        {
            $str = preg_replace('/[^a-z0-9_]/i', $seperator, $str);
        }
        return $str;
    }

    function showFilters($num_page = true, $order = false, $category_select = false)
    {
        $items_per_page = !empty($_GET['pip']) ? $_GET['pip'] : 20;
        $condition = !empty($_GET['psort']) ? $_GET['psort'] : 'pos_asc';
        $filter_category = !empty($_GET['pcat']) ? $_GET['pcat'] : 0;

        $filter1 = $items_per_page == 20 ? "20" : "<a href=\"{$this->template_parser->content['current_url']}&pip=20&psort=$condition&pcat=$filter_category\">20</a>";
        $filter2 = $items_per_page == 50 ? "50" : "<a href=\"{$this->template_parser->content['current_url']}&pip=50&psort=$condition&pcat=$filter_category\">50</a>";
        $filter3 = $items_per_page == 100 ? "100" : "<a href=\"{$this->template_parser->content['current_url']}&pip=100&psort=$condition&pcat=$filter_category\">100</a>";

        $sort7 = $condition == 'a_z' ? "A - Z" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=a_z&pcat=$filter_category\">A - Z</a>";
        $sort8 = $condition == 'z_a' ? "Z - A" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=z_a&pcat=$filter_category\">Z - A</a>";
        $sort3 = $condition == 'newest' ? "Newest first" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=newest&pcat=$filter_category\">Newest first</a>";
        $sort4 = $condition == 'oldest' ? "Oldest first" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=oldest&pcat=$filter_category\">Oldest first</a>";
        $sort5 = $condition == 'most_viewed' ? "Most viewed" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=most_viewed&pcat=$filter_category\">Most viewed</a>";
        $sort6 = $condition == 'least_viewed' ? "Least viewed" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=least_viewed&pcat=$filter_category\">Least viewed</a>";
        $sort1 = $condition == 'pos_asc' ? "Position ASC" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=pos_asc&pcat=$filter_category\">Position ASC</a>";
        $sort2 = $condition == 'pos_desc' ? "Position DESC" : "<a href=\"{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=pos_desc&pcat=$filter_category\">Position DESC</a>";

        $this->template_parser->content['view.filter'] = "<div id=\"filter\">\n";

        if ($category_select)
        {
            $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');
            //$this->debug($filter_category);
            $filter_categories = explode(',', $filter_category);

            $this->template_parser->content['view.filter'] .= "<table>\n";

            foreach ($filter_categories as $filter_category)
            {
                $category_rows .= "<tr><td>Category:</td><td><select name=\"category_filters\" onchange=\"generateCategoriesList();\">";
                $category_rows .="<option value=\"0\">None</option>";
                foreach ($categories as $category)
                {
                    $selected = '';
                    if ($filter_category == $category['id'])
                    {
                        $selected = ' selected="selected"';
                    }
                    $category_rows .= "<option value=\"{$category['id']}\"$selected>{$category['name_with_path']}</option>";
                }
                $category_rows .= "</select>&nbsp;<a href=\"javascript:\" onclick=\"$(this).parent().parent().remove();generateCategoriesList();\">remove</a></td></tr>";
            }
            $this->template_parser->content['view.filter'] .= $category_rows;

            $category_row = "<tr><td>Category:</td><td><select name=\"category_filters\" onchange=\"generateCategoriesList();\">";
            $category_row .="<option value=\"0\">None</option>";
            foreach ($categories as $category)
            {
                $category_row .= "<option value=\"{$category['id']}\">{$category['name_with_path']}</option>";
            }
            $category_row .= "</select>&nbsp;<a href=\"javascript:\" onclick=\"$(this).parent().parent().remove();generateCategoriesList();\">remove</a></td></tr>";

            $this->template_parser->content['view.filter'] .= "
            <tr>\n
                <td>&nbsp;</td>\n
                <td><a id=\"add-filter-link\" href=\"javascript:\">add category filter</a></td>\n
            </tr>\n
            <script type=\"text/javascript\">\n
            var category_count = 0;\n
            $(document).ready(function() {\n
                $('#add-filter-link').click(function(){\n
                    category_count++;\n
                   $(this).parent().parent().before('$category_row');\n
                });\n
            });\n
            function generateCategoriesList()
            {
                var cat_list = $('select[name=\"category_filters\"]');
                var cat_list_size = cat_list.length;
                var categories_list = \"\";
                    
                cat_list.each(function (index){
                    var connector = '';
                    if (index < (cat_list_size - 1))
                    {
                        connector = ',';
                    }

                    var value = $(this).val();
                    if (value != null || value != '')
                    {
                        categories_list += value + connector;
                    }
                });
                window.location = '{$this->template_parser->content['current_url']}&pip=$items_per_page&psort=$condition&pcat=' + categories_list;
            }
            </script>\n";
            $this->template_parser->content['view.filter'] .= "</table>\n";
        }

        if ($num_page)
        {
            $this->template_parser->content['view.filter'] .= "
            Show: $filter1\n
             | $filter2\n
             | $filter3\n
            &nbsp; &nbsp;";
        }

        if ($order)
        {
            $this->template_parser->content['view.filter'] .= "
            <br /><br />Sort by: $sort1\n
             | $sort2\n
             | $sort3\n
             | $sort4\n
             | $sort5\n
             | $sort6\n
             | $sort7\n
             | $sort8\n
            &nbsp; &nbsp;";
        }

        $this->template_parser->content['view.filter'] .= "</div>\n";
    }

    function paginate($all_items = array(), $display_type = 'default', $num_per_page = 20)
    {
        $items = array();

        if ($items_per_page < 1)
        {
            $items_per_page = 1;
        }

        $items_per_page = !empty($_GET['pip']) ? $_GET['pip'] : $num_per_page;
        //get max items
        $max_items = count($all_items);

        if ($max_items <= 0)
        {
            return array();
        }

        //get total page
        $total_pages = ceil($max_items / $items_per_page);

        //get current page
        $current_page = !empty($_GET['pcp']) ? $_GET['pcp'] : 1;
        if ($current_page < 1)
        {
            $current_page = 1;
        }

        $sort = !empty($_GET['psort']) ? $_GET['psort'] : 'pos_asc';
        $filter_category = !empty($_GET['pcat']) ? $_GET['pcat'] : -1;

        //get limit range
        $from = ($current_page - 1) * $items_per_page;

        $to = $from + $items_per_page - 1;
        if ($to > $max_items)
        {
            $to = $max_items - 1;
        }

        //get list of items
        for ($i = $from; $i <= $to; $i++)
        {
            $items[] = $all_items[$i];
        }

        $p_from = $from + 1;
        $p_to = $to + 1;
        $p_num_pages = 7;
        $p_num_pages_side = floor($p_num_pages / 2);

        switch ($display_type)
        {
            case 'rana':
                if ($items_per_page == 999999)
                {
                    $class = ' hide';
                }
                $this->template_parser->content['view.paginator'] = "<div class=\"pagination$class\">\n";
                $this->template_parser->content['view.paginator'] .= "{$this->template_parser->content['lang.IM_paginator_page']}: ";
                for ($side_page = $current_page - $p_num_pages_side; $side_page < $current_page; $side_page++)
                {
                    if ($side_page > 0)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a> | \n";
                    }
                }
                $this->template_parser->content['view.paginator'] .= " <span class=\"current\">$current_page</span> | \n";
                for ($side_page = $current_page + 1; $side_page <= $current_page + $p_num_pages_side; $side_page++)
                {
                    if ($side_page <= $total_pages)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a> | \n";
                    }
                }
                $this->template_parser->content['view.paginator'] .= "<a href=\"{$this->template_parser->content['current_url']}&pcp=1&pip=999999&psort=$sort&pcat=$filter_category\">View all</a>\n";
                $this->template_parser->content['view.paginator'] .= "</div>\n";
                break;
            case 'ttgallery':
                $this->template_parser->content['view.paginator'] = "<div id=\"pagination\">\n";
                //$this->template_parser->content['view.paginator'] .= "<strong>$p_from - $p_to</strong> {$this->template_parser->content['lang.IM_paginator_in']} <strong>$max_items</strong> &nbsp;<span class=\"light\">|</span>&nbsp; {$this->template_parser->content['lang.IM_paginator_page']} ";
                for ($side_page = $current_page - $p_num_pages_side; $side_page < $current_page; $side_page++)
                {
                    if ($side_page > 0)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a>\n";
                    }
                }
                $this->template_parser->content['view.paginator'] .= " <a href=\"javascript:\" class=\"current\">$current_page</a>\n";
                for ($side_page = $current_page + 1; $side_page <= $current_page + $p_num_pages_side; $side_page++)
                {
                    if ($side_page <= $total_pages)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a>\n";
                    }
                }

                $this->template_parser->content['view.paginator'] .= "</div>\n";
                break;
            default:
                $this->template_parser->content['view.paginator'] = "<div class=\"paging\">\n";
                $this->template_parser->content['view.paginator'] .= "<strong>$p_from - $p_to</strong> {$this->template_parser->content['lang.IM_paginator_in']} <strong>$max_items</strong> &nbsp;<span class=\"light\">|</span>&nbsp; {$this->template_parser->content['lang.IM_paginator_page']} ";
                for ($side_page = $current_page - $p_num_pages_side; $side_page < $current_page; $side_page++)
                {
                    if ($side_page > 0)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a>\n";
                    }
                }
                $this->template_parser->content['view.paginator'] .= " <span class=\"current\">$current_page</span>\n";
                for ($side_page = $current_page + 1; $side_page <= $current_page + $p_num_pages_side; $side_page++)
                {
                    if ($side_page <= $total_pages)
                    {
                        $this->template_parser->content['view.paginator'] .= " <a href=\"{$this->template_parser->content['current_url']}&pcp=$side_page&pip=$items_per_page&psort=$sort&pcat=$filter_category\">$side_page</a>\n";
                    }
                }

                $this->template_parser->content['view.paginator'] .= "</div>\n";
        }



        return $items;
    }

    function handleFileUpload($allow_types = array(), $parent_type = 'item', $parent_id = -1, $file_index = -1)
    {
        if (!empty($_FILES['file']['name']))
        {
            $dir = '';
            if ($parent_type == 'category')
            {
                $dir = 'categories';
            }
            elseif($parent_type == 'item')
            {
                $dir = 'items';
            }

            $num_images = count($_FILES['file']['name']);

            $from = $file_index > -1 ? $file_index : 0;
            $to = $file_index > -1 ? $file_index + 1 : $num_images;

            for ($i = $from; $i < $to; $i++)
            {
                if ($_FILES['file']['error'][$i] == 0)
                {
                    $tmp_path = $_FILES['file']['tmp_name'][$i];
                    $target_path = MODX_BASE_PATH . 'assets/modules/item_manager/uploads/' . $dir . '/' . $parent_id . '/';

                    //$finfo = finfo_open(FILEINFO_MIME_TYPE);
                    //$mime_type = finfo_file($finfo, $tmp_path);
                    //finfo_close($finfo);

                    $image_info = getimagesize($tmp_path);
                    $mime_type = $image_info['mime'];

                    $image_type = exif_imagetype($tmp_path);
                    $image_ext = image_type_to_extension($image_type, true);

                    $file_name = $this->generateRandomString(8) . $image_ext;
                    $file_size = $_FILES['file']['size'][$i];

                    if (in_array($mime_type, $allow_types))
                    {
                        if (!file_exists($target_path))
                        {
                            mkdir($target_path, 0, true);
                            chmod($target_path, 0755);
                        }

                        copy($tmp_path, $target_path . $file_name);
                        $table_name = $this->modx->getFullTableName('item_manager_files');

                        $query_exist_files = "SELECT * FROM $table_name WHERE type = '$parent_type' AND owner_id = $parent_id";
                        $result_exist_files = $this->modx->db->query($query_exist_files);
                        $num_exist_files = $this->modx->db->getRecordCount ($result_exist_files);

                        if (($i == 0 && $num_exist_files <= 0) || $file_index > -1)
                        {
                            $query_insert_file = "INSERT INTO $table_name (file_name, file_size, mime_type, type, is_primary, owner_id) VALUES ('$file_name', $file_size, '$mime_type', '$parent_type', 1, $parent_id)";
                        }
                        else
                        {
                            $query_insert_file = "INSERT INTO $table_name (file_name, file_size, mime_type, type, is_primary, owner_id) VALUES ('$file_name', $file_size, '$mime_type', '$parent_type', 0, $parent_id)";
                        }
                        $inserted_id = $this->modx->db->query($query_insert_file);
                    }
                    else
                    {
                        $errors[] = $this->template_parser->content['lang.IM_error_content_type_not_allow'];
                    }

                }
            }
        }
    }

    function removeDir($dir)
    {
        if (is_dir($dir))
        {
            $objects = scandir($dir);
            foreach ($objects as $object)
            {
                if ($object != "." && $object != "..")
                {
                    if (filetype($dir . "/" . $object) == "dir")
                        rrmdir($dir . "/" . $object); else
                        unlink($dir . "/" . $object);
                }
            }
            reset($objects);
            rmdir($dir);
        }
    }

    function removeFile($type, $parent_id, $action = 'delete_all', $file_id = null)
    {
        if (is_numeric($parent_id))
        {
            $table_name = $this->modx->getFullTableName('item_manager_files');

            if ($action == 'delete_one' && !empty($file_id) && is_numeric($file_id))
            {
                $query_remove_file = "DELETE FROM $table_name WHERE type = '$type' AND owner_id = $parent_id AND id = $file_id";
                $this->modx->db->query($query_remove_file);
            }
            elseif ($action == 'delete_all')
            {
                $dir = '';
                if ($parent_type == 'category')
                {
                    $dir = 'categories';
                }
                elseif($parent_type == 'item')
                {
                    $dir = 'items';
                }

                $this->removeDir(MODX_BASE_PATH . 'assets/modules/item_manager/uploads/' . $dir . '/' . $parent_id . '/');
                $query_remove_file = "DELETE FROM $table_name WHERE type = '$type' AND owner_id = $parent_id";
                $this->modx->db->query($query_remove_file);
            }
        }
    }

    function makeFilePrimary($type, $category_id, $file_id)
    {
        $table_name = $this->modx->getFullTableName('item_manager_files');
        $query_update_all_files = "UPDATE $table_name SET is_primary = 0 WHERE type = '$type' AND owner_id = $category_id";
        $this->modx->db->query($query_update_all_files);
        $query_update_primary = "UPDATE $table_name SET is_primary = 1 WHERE type = '$type' AND owner_id = $category_id AND id = $file_id";
        $this->modx->db->query($query_update_primary);
    }

    function getFiles($type, $parent_id)
    {
        if (!empty($parent_id) && is_numeric($parent_id))
        {
            $files = array();
            $table_name = $this->modx->getFullTableName('item_manager_files');
            $query_get_files = "SELECT * FROM $table_name WHERE type = '$type' AND owner_id = $parent_id";
            $result_get_files = $this->modx->db->query($query_get_files);
            while ($file_row = $this->modx->db->getRow($result_get_files))
            {
                $files[] = $file_row;
            }
            return $files;
        }
        else
        {
            return array();
        }
    }

    function getPrimaryFileIndex($files)
    {
        $primary_file_index = 0;
        $count = 0;
        foreach ($files as $file)
        {
            if ($file['is_primary'] == 1)
            {
                $primary_file_index =$count;
                break;
            }
            $count++;
        }
        return $primary_file_index;
    }

    function process()
    {
        $this->show_debug = true;
        $this->data = $_REQUEST['data'];

        $this->template_parser->content['action_id'] = $_REQUEST['a'];
        $this->template_parser->content['module_id'] = $_REQUEST['id'];
        $this->template_parser->content['module_url'] = $this->url = "index.php?a={$_REQUEST['a']}&id={$_REQUEST['id']}";
        $this->template_parser->content['current_url'] = $this->url . "&page={$this->page}&gallery_id={$_REQUEST['gallery_id']}";

        $items_per_page = !empty($_GET['pip']) ? $_GET['pip'] : 20;
        $current_page = !empty($_GET['pcp']) ? $_GET['pcp'] : 1;
        $condition = !empty($_GET['psort']) ? $_GET['psort'] : 'pos_asc';
        $filter_category = !empty($_GET['pcat']) ? $_GET['pcat'] : -1;
        $this->template_parser->content['current_pagination_url'] = $this->template_parser->content['current_url'] . "&pip=$items_per_page&pcp=$current_page&psort=$condition&pcat=$filter_category";

        $this->showNavigator();

        if (empty($_REQUEST['a']))
        {
            switch ($this->page)
            {
                default:
                    break;
            }
            
        }
        else
        {
            switch ($this->page)
            {
                default:
                case 'items':
                case 'view_all_items':
                    $this->viewAllItems();
                    break;
                case 'add_new_item':
                    $this->addNewItem();
                    break;
                case 'edit_item':
                    $this->editItem($_REQUEST['item_id']);
                    break;
                case 'reorder_items':
                    $this->reorderItems('items');
                    break;
                case 'add_multiple_items':
                    $this->addMultipleItems();
                    break;
                case 'categories':
                case 'view_all_categories':
                    $this->viewAllCategories();
                    break;
                case 'add_new_category':
                    $this->addNewCategory();
                    break;
                case 'edit_category':
                    $this->editCategory($_REQUEST['category_id']);
                    break;
                case 'reorder_categories':
                    $this->reorderItems('categories');
                    break;
                case 'templates':
                    $this->templates();
                    break;
                case 'config':
                    $this->config();
                    break;
            }
        }
        //$this->debug($this->page_id);
        //$this->debug($_REQUEST);
        //$this->debug($_SESSION['login']);
        //$this->debug($_SERVER);
    }

    function showNavigator()
    {
        $this->template_parser->content['subnav.active_items'] = ' class="hide"';
        $this->template_parser->content['subnav.active_categories'] = ' class="hide"';

        switch ($this->page)
        {
            default:
            case 'items':
            case 'view_all_items':
                $this->template_parser->content['nav.active_items'] = ' class="active"';
                $this->template_parser->content['subnav.active_items'] = ' class="show"';
                $this->template_parser->content['subnav.active_view_all_items'] = ' class="active"';
                break;
            case 'add_new_item':
                $this->template_parser->content['nav.active_items'] = ' class="active"';
                $this->template_parser->content['subnav.active_items'] = ' class="show"';
                $this->template_parser->content['subnav.active_add_new_item'] = ' class="active"';
                break;
            case 'edit_item':
                $this->template_parser->content['nav.active_items'] = ' class="active"';
                $this->template_parser->content['subnav.active_items'] = ' class="show"';
                break;
            case 'reorder_items':
                $this->template_parser->content['nav.active_items'] = ' class="active"';
                $this->template_parser->content['subnav.active_items'] = ' class="show"';
                $this->template_parser->content['subnav.active_reorder_items'] = ' class="active"';
                break;
            case 'add_multiple_items':
                $this->template_parser->content['nav.active_items'] = ' class="active"';
                $this->template_parser->content['subnav.active_items'] = ' class="show"';
                $this->template_parser->content['subnav.active_add_multiple_items'] = ' class="active"';
                break;
            case 'categories':
            case 'view_all_categories':
                $this->template_parser->content['nav.active_categories'] = ' class="active"';
                $this->template_parser->content['subnav.active_categories'] = ' class="show"';
                $this->template_parser->content['subnav.active_view_all_categories'] = ' class="active"';
                break;
            case 'add_new_category':
                $this->template_parser->content['nav.active_categories'] = ' class="active"';
                $this->template_parser->content['subnav.active_categories'] = ' class="show"';
                $this->template_parser->content['subnav.active_add_new_category'] = ' class="active"';
                break;
            case 'edit_category':
                $this->template_parser->content['nav.active_categories'] = ' class="active"';
                $this->template_parser->content['subnav.active_categories'] = ' class="show"';
                break;
            case 'reorder_categories':
                $this->template_parser->content['nav.active_categories'] = ' class="active"';
                $this->template_parser->content['subnav.active_categories'] = ' class="show"';
                $this->template_parser->content['subnav.active_reorder_categories'] = ' class="active"';
                break;
            case 'templates':
                $this->template_parser->content['nav.active_templates'] = ' class="active"';
                break;
            case 'config':
                $this->template_parser->content['nav.active_config'] = ' class="active"';
                break;

        }
        $this->template_parser->content['view.navigator'] = $this->template_parser->parseTemplate('navigator.tpl', $this->template_parser->content);
    }

    function getItemCategories($id)
    {
        $categories = array();
        $table_name = $this->modx->getFullTableName('item_manager_categories_items');
        $query = "SELECT DISTINCT category_id FROM $table_name WHERE item_id = $id";
        $result = $this->modx->db->query($query);

        $items_categories = array();
        while ($row = $this->modx->db->getRow($result))
        {
            $items_categories[] = $row['category_id'];
        }

        $category_ids = implode(',', $items_categories);

        $categories_table_name = $this->modx->getFullTableName('item_manager_categories');
        $query_categories = "SELECT * FROM $categories_table_name WHERE id IN ($category_ids)";
        $result_categories = $this->modx->db->query($query_categories);
        while ($category_row = $this->modx->db->getRow($result_categories))
        {
            $categories[] = $category_row;
        }

        return $categories;
    }

    function getCategory($id)
    {
        $table_name = $this->modx->getFullTableName('item_manager_categories');
        $query = "SELECT * FROM $table_name WHERE id = $id";
        $result = $this->modx->db->query($query);
        $row = $this->modx->db->getRow($result);
        return $row;
    }

    function getCategoryByName($name)
    {
        $table_name = $this->modx->getFullTableName('item_manager_categories');
        $query = "SELECT * FROM $table_name WHERE name = '$name'";
        $result = $this->modx->db->query($query);
        $row = $this->modx->db->getRow($result);
        return $row;
    }

    function getItem($id)
    {
        $table_name = $this->modx->getFullTableName('item_manager_items');
        $query = "SELECT * FROM $table_name WHERE id = $id";
        $result = $this->modx->db->query($query);
        $row = $this->modx->db->getRow($result);
        return $row;
    }

    function getAllItems($category_id = null, $order = "")
    {
        $table_name = $this->modx->getFullTableName('item_manager_items');

        $filter_category = !empty($_GET['pcat']) ? $_GET['pcat'] : -1;

        $categories_items = array();
        $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');
        $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name WHERE category_id IN ($filter_category)";

        if (!empty($category_id) && is_numeric($category_id) && $category_id > 0)
        {
            $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name WHERE category_id = $category_id";
        }
        else
        {
            //show all items when there is no filter category and in admin
            if ($filter_category < 1 && !empty($_REQUEST['a']))
            {
                $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name";
            }
            else
            {
                $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name WHERE category_id IN ($filter_category)";
            }
        }

        $sort = !empty($_GET['psort']) ? $_GET['psort'] : 'pos_asc';

        if (empty($order))
        {
            switch ($sort)
            {
                case 'a_z':
                    $order = "ORDER BY name ASC";
                    break;
                case 'z_a':
                    $order = "ORDER BY name DESC";
                    break;
                case 'newest':
                    $order = "ORDER BY created DESC";
                    break;
                case 'oldest':
                    $order = "ORDER BY created ASC";
                    break;
                case 'most_viewed':
                    $order = "ORDER BY hits DESC";
                    break;
                case 'least_viewed':
                    $order = "ORDER BY hits ASC";
                    break;
                case 'pos_asc':
                    $order = "ORDER BY position ASC";
                    break;
                case 'pos_desc':
                    $order = "ORDER BY position DESC";
                    break;
            }
        }

        //$this->debug($query_categories_items);
        $result_categories_items = $this->modx->db->query($query_categories_items);
        while ($row = $this->modx->db->getRow($result_categories_items))
        {
            $categories_items[] = $row['item_id'];
        }
        $item_ids = implode(',', $categories_items);
        //$this->debug($item_ids);

        if (empty($item_ids))
        {
            $item_ids = 0;
        }

        $query_all_items = "SELECT * FROM $table_name WHERE id IN ($item_ids) $order";
        //$this->debug($query_all_items);
        $result_all_items = $this->modx->db->query($query_all_items);

        $all_items = array();
        while ($item_row = $this->modx->db->getRow($result_all_items))
        {
            $category_table_name = $this->modx->getFullTableName('item_manager_categories');
            $items_categories = array();
            $query_category_ids = "SELECT DISTINCT category_id FROM $categories_items_table_name WHERE item_id = {$item_row['id']}";
            $result_category_ids = $this->modx->db->query($query_category_ids);
            while ($row = $this->modx->db->getRow($result_category_ids))
            {
                $items_categories[] = $row['category_id'];
            }
            $category_ids = implode(',', $items_categories);
            if (empty($category_ids))
            {
                $category_ids = 0;
            }
            
            $query_category = "SELECT * FROM $category_table_name WHERE id IN ($category_ids)";
            $result_category = $this->modx->db->query($query_category);
            while ($category_row = $this->modx->db->getRow($result_category))
            {
                $item_row['category'][] = $category_row;
            }

            $file_table = $this->modx->getFullTableName('item_manager_files');
            $query_files = "SELECT * FROM $file_table WHERE type = 'item' AND owner_id = {$item_row['id']}";
            $result_files = $this->modx->db->query($query_files);

            $files = array();
            while ($file_row = $this->modx->db->getRow($result_files))
            {
                $files[] = $file_row;
            }
            $item_row['files'] = $files;

            $all_items[] = $item_row;
        }

        return $all_items;
    }

    function viewAllItems()
    {
        $table_name = $this->modx->getFullTableName('item_manager_items');

        $action = $_REQUEST['action'];
        if (!empty($action))
        {
            $item_id = $_REQUEST['item_id'];
            if ($action == 'delete_item' && !empty($item_id) && is_numeric($item_id))
            {
                $this->modx->db->delete($table_name, "id = $item_id");
                $this->removeFile('item', $item_id);
            }
        }

        $all_items = $this->getAllItems();
        $this->showFilters(true, true, true);
        $items = $this->paginate($all_items);

        $this->template_parser->content['table_row.items'] = '';
        foreach ($items as $item)
        {
            $image = "<img src=\"{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=25&height=25&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][0]['file_name']}\" />";
            $created = date('Y-M-d, H:i:s A', strtotime($item['created']));
            $modified = date('Y-M-d, H:i:s A', strtotime($item['modified']));;
            $categories_name = "";
            $category_count = 0;
            $categories_count = sizeof($item['category']);
            foreach ($item['category'] as $category_name)
            {
                $add = ", ";
                if ($category_count == $categories_count - 1)
                {
                    $add = "";
                }

                $categories_name .= "{$category_name['name']}$add";
                $category_count++;
            }
            $this->template_parser->content['table_row.items'] .= "
            <tr>\n
            <td class=\"id\">{$item['id']}</td>\n
            <td class=\"thumb\">$image</td>\n
            <td class=\"name\"><a href=\"{$this->url}&page=edit_item&item_id={$item['id']}\">{$item['name']}</a></td>\n
            <td class=\"category\">$categories_name</td>\n
            <td class=\"date\">$created</td>\n
            <td class=\"date\">$modified</td>\n
            <!-- <td class=\"hits\">{$item['hits']}</td> -->\n
            <td class=\"action\"><a href=\"{$this->template_parser->content['current_pagination_url']}&action=delete_item&item_id={$item['id']}\" onclick=\"return confirm('{$this->template_parser->content['lang.IM_msg_confirm_deletion']}')\">Delete</a></td>\n
            </tr>\n
            ";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('view_all_items.tpl', $this->template_parser->content);
    }

    function addNewItem()
    {
        if (!empty($this->data))
        {
            $errors = array();
            if (empty($this->data['Item']['name']))
            {
                $errors[] = $this->template_parser->content['lang.IM_error_empty_item_name'];
            }

            if (empty($errors))
            {
                $table_name = $this->modx->getFullTableName('item_manager_items');
                $fields['name'] = $this->data['Item']['name'];
                $fields['code'] = $this->data['Item']['code'];
                $fields['price'] = $this->data['Item']['price'];
                $fields['description'] = $this->data['Item']['description'];
                $fields['size'] = $this->data['Item']['size'];
                $fields['text_01'] = $this->data['Item']['text_01'];
                $fields['created'] = $fields['modified'] = date('Y-m-d H:i:s', time());
                $fields['permalink'] = $this->createPermalink($fields['name']);
                if (!empty($this->data['Item']['category_id']))
                {
                    $otherfields['category_id'] = $this->data['Item']['category_id'];
                }
                else
                {
                    $otherfields['category_id'] = 0;
                }

                $item_id = $this->modx->db->insert($fields, $table_name);

                if ($item_id)
                {
                    $this->addCategoriesToItem($otherfields['category_id'], $item_id);
                    $allow_types = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
                    $this->handleFileUpload($allow_types, 'item', $item_id);
                    $this->showMessage($this->template_parser->content['lang.IM_msg_add_new_item'], 'successmsg');
                }
            }
            else
            {
                $this->showMessage($errors, 'errormsg');
            }
        }

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\">{$category['name_with_path']}</option>";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('add_new_item.tpl', $this->template_parser->content);
    }

    function editItem($item_id)
    {
        $action = $_REQUEST['action'];
        if (!empty($action))
        {
            $file_id = $_REQUEST['file_id'];
            if ($action == 'delete_file' && !empty($file_id) && is_numeric($file_id))
            {
                $this->removeFile('item', $item_id, 'delete_one', $file_id);
            }

            $category_id = $_REQUEST['category_id'];
            if ($action == 'delete_category' && !empty($category_id) && is_numeric($category_id))
            {
                $this->removeCategoryFromItem($category_id, $item_id);
            }

            if ($action == 'make_primary' && !empty($file_id) && is_numeric($file_id))
            {
                $this->makeFilePrimary('item', $item_id, $file_id);
            }
        }

        if (empty($item_id))
        {
            $this->showMessage($this->template_parser->content['lang.IM_error_item_not_found'], 'errormsg');
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('edit_item.tpl', $this->template_parser->content);
            return;
        }
        $table_name = $this->modx->getFullTableName('item_manager_items');

        if (empty($this->data))
        {
            $query_item = "SELECT * FROM $table_name WHERE id = $item_id";
            $result_item = $this->modx->db->query($query_item);
            $this->data['Item'] = $this->modx->db->getRow($result_item);
        }
        else
        {
            $errors = array();
            if (empty($this->data['Item']['name']))
            {
                $errors[] = $this->template_parser->content['lang.IM_error_empty_item_name'];
            }

            $query_item = "SELECT * FROM $table_name WHERE id = $item_id";
            $result_item = $this->modx->db->query($query_item);
            $item = $this->modx->db->getRow($result_item);

            if (empty($errors))
            {
                $fields['name'] = $this->data['Item']['name'];
                $fields['code'] = $this->data['Item']['code'];
                $fields['price'] = $this->data['Item']['price'];
                $fields['description'] = $this->data['Item']['description'];
                $fields['size'] = $this->data['Item']['size'];
                $fields['text_01'] = $this->data['Item']['text_01'];
                $fields['modified'] = date('Y-m-d H:i:s', time());
                $fields['permalink'] = $this->createPermalink($fields['name']);
                if (!empty($this->data['Item']['category_id']))
                {
                    $otherfields['category_id'] = $this->data['Item']['category_id'];
                }
                else
                {
                    $otherfields['category_id'] = 0;
                }

                $update_success = $this->modx->db->update($fields, $table_name, "id=$item_id");

                if ($update_success)
                {
                    $this->removeAllCategoriesFromItem($item_id);
                    $this->addCategoriesToItem($otherfields['category_id'], $item_id, true);
                    $allow_types = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
                    $this->handleFileUpload($allow_types, 'item', $item_id);
                    $this->showMessage($this->template_parser->content['lang.IM_msg_edit_item'], 'successmsg');
                }
            }
            else
            {
                $this->showMessage($errors, 'errormsg');
            }
        }

        $this->template_parser->content['item.id'] = $this->data['Item']['id'];
        $this->template_parser->content['item.name'] = $this->data['Item']['name'];
        $this->template_parser->content['item.code'] = $this->data['Item']['code'];
        $this->template_parser->content['item.price'] = $this->data['Item']['price'];
        $this->template_parser->content['item.description'] = $this->data['Item']['description'];
        $this->template_parser->content['item.size'] = $this->data['Item']['size'];
        $this->template_parser->content['item.text_01'] = $this->data['Item']['text_01'];
        $this->template_parser->content['item.category_id'] = $this->data['Item']['category_id'];

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\">{$category['name_with_path']}</option>";
        }

        $item_categories = $this->getItemCategories($item_id);

        $item_categories_count = 1;
        foreach ($item_categories as $item_category)
        {
            $edit_url = "{$this->url}&page=edit_item&item_id=$item_id";
            $delete_link = "<a href=\"$edit_url&action=delete_category&category_id={$item_category['id']}\" onclick=\"return confirm('{$this->template_parser->content['lang.IM_msg_confirm_file_category_deletion']}')\">Delete</a>";
            $this->template_parser->content['table_row.categories'] .= "
            <tr>\n
            <td class=\"col1\">Category $item_categories_count</td>\n
            <td class=\"col2\">\n
            <select name=\"data[Item][category_id][]\" class=\"dropdown\">\n";
            foreach ($categories as $category)
            {
                $selected = '';
                if ($item_category['id'] == $category['id'])
                {
                    $selected = ' selected="selected"';
                }
                $this->template_parser->content['table_row.categories'] .= "<option value=\"{$category['id']}\"$selected>{$category['name_with_path']}</option>";
            }
            $this->template_parser->content['table_row.categories'] .= "
            </select> $delete_link\n
            </td>\n
            </tr>\n";
            $item_categories_count++;
        }

        $this->set('item_categories_count', $item_categories_count - 1);

        $files = $this->getFiles('item', $item_id);

        $file_count = 1;
        foreach ($files as $file)
        {
            $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=50&height=50&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item_id}/{$file['file_name']}";
            $edit_url = "{$this->url}&page=edit_item&item_id=$item_id";
            $delete_link = "<a href=\"$edit_url&action=delete_file&file_id={$file['id']}\" onclick=\"return confirm('{$this->template_parser->content['lang.IM_msg_confirm_file_deletion']}')\">Delete</a>";

            $primary_link = "Primary";
            if (!$file['is_primary'])
            {
                $primary_link = "<a href=\"$edit_url&action=make_primary&file_id={$file['id']}\">Make primary</a>";
            }
            $this->template_parser->content['table_row.images'] .= "
            <tr>\n
            <td class=\"col1\">Image $file_count</td>\n
            <td class=\"col2\">\n
                <img src=\"$image_src\" />\n
                 $delete_link | $primary_link\n
            </td>\n
            </tr>\n
            ";
            $file_count++;
        }

        $this->set("file_count", $file_count - 1);

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('edit_item.tpl', $this->template_parser->content);
    }

    function addMultipleItems()
    {
        if (!empty($this->data['Item']['name']))
        {
            $num_items = count($this->data['Item']['name']);
            for ($i = 0; $i < $num_items; $i++)
            {
                $errors = array();
                if (empty($this->data['Item']['category_id']))
                {
                    $errors[] = $this->template_parser->content['lang.IM_error_empty_category'];
                }

                if (empty($this->data['Item']['name'][$i]))
                {
                    $errors[] = $this->template_parser->content['lang.IM_error_empty_item_name'];
                }

                if (empty($errors))
                {
                    $table_name = $this->modx->getFullTableName('item_manager_items');
                    $fields['name'] = $this->data['Item']['name'][$i];
                    $fields['created'] = $fields['modified'] = date('Y-m-d H:i:s', time());
                    $fields['permalink'] = $this->createPermalink($fields['name']);
                    if (!empty($this->data['Item']['category_id']))
                    {
                        $otherfields['category_id'] = $this->data['Item']['category_id'];
                    }
                    else
                    {
                        $otherfields['category_id'] = 0;
                    }

                    $item_id = $this->modx->db->insert($fields, $table_name);

                    if ($item_id)
                    {
                        $this->addCategoriesToItem($otherfields['category_id'], $item_id);
                        $allow_types = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
                        $this->handleFileUpload($allow_types, 'item', $item_id, $i);
                        $this->showMessage($this->template_parser->content['lang.IM_msg_add_new_item'], 'successmsg');
                    }
                }
                else
                {
                    $this->showMessage($errors, 'errormsg');
                }
            }
        }

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\">{$category['name_with_path']}</option>";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('add_multiple_items.tpl', $this->template_parser->content);
    }

    function addCategoriesToItem($category_ids, $item_id, $reverse_array = false)
    {
        $items_table_name = $this->modx->getFullTableName('item_manager_items');
        $categories_table_name = $this->modx->getFullTableName('item_manager_categories');
        $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');

        if (is_array($category_ids) && sizeof($category_ids) > 0)
        {
            if ($reverse_array)
            {
                $category_ids = array_reverse($category_ids);
            }
            foreach ($category_ids as $category_id)
            {
                $fields['item_id'] = $item_id;
                $fields['category_id'] = $category_id;
                $result = $this->modx->db->select('id', $categories_items_table_name, "category_id=$category_id AND item_id=$item_id");
                $row_count = $this->modx->db->getRecordCount($result);
                if ($row_count <= 0)
                {
                    $this->modx->db->insert($fields, $categories_items_table_name);
                }
            }
        }
    }

    function removeCategoryFromItem($category_id, $item_id)
    {
        $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');
        $this->modx->db->delete($categories_items_table_name, "category_id = $category_id AND item_id = $item_id");
    }

    function removeAllCategoriesFromItem($item_id)
    {
        $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');
        $this->modx->db->delete($categories_items_table_name, "item_id = $item_id");
    }

    function getCategoriesTree($root_category_id = 0, $get_children = true, $path_prefix = '', $order = '', $category_table = 'modx_item_manager_categories', &$categories = array(), $level = 0)
    {
        $root_conditions = 'parent_id = 0';
        if (is_numeric($root_category_id))
        {
            $root_conditions = "parent_id = $root_category_id";
        }

        $query_root_categories = "SELECT * FROM $category_table WHERE $root_conditions $order";
        //$this->debug($query_root_categories);
        $result_root_categories = $this->modx->db->query(mysql_real_escape_string($query_root_categories));
        while ($row = $this->modx->db->getRow($result_root_categories))
        {
            if (empty($row['parent_id']))
            {
                $level = 0;
            }

            $path = '';
            if ($level > 0)
            {
                for ($i = 1; $i < $level; $i++)
                {
                    $path .= "&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                $path .= $path_prefix;
            }

            $row['level'] = $level;
            $row['name_with_path'] = $path . $row['name'];

            $query_parent = "SELECT * FROM $category_table WHERE id = {$row['parent_id']} $order";
            $result_parent = $this->modx->db->query($query_parent);
            $parent_row = $this->modx->db->getRow($result_parent);
            $row['parent'] = $parent_row;

            $file_table = $this->modx->getFullTableName('item_manager_files');
            $query_files = "SELECT * FROM $file_table WHERE type = 'category' AND owner_id = {$row['id']}";
            $result_files = $this->modx->db->query($query_files);

            $files = array();
            while ($file_row = $this->modx->db->getRow($result_files))
            {
                $files[] = $file_row;
            }
            $row['files'] = $files;

            $categories_items = array();
            $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');
            $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name WHERE category_id = {$row['id']}";

            $result_categories_items = $this->modx->db->query($query_categories_items);
            while ($item_row = $this->modx->db->getRow($result_categories_items))
            {
                $categories_items[] = $item_row['item_id'];
            }
            $item_ids = implode(',', $categories_items);

            if (empty($item_ids))
            {
                $item_ids = 0;
            }

            $item_table = $this->modx->getFullTableName('item_manager_items');
            $query_items = "SELECT * FROM $item_table WHERE id IN ($item_ids)";
            $result_items = $this->modx->db->query($query_items);

            $items = array();
            while ($item_row = $this->modx->db->getRow($result_items))
            {
                $items[] = $item_row;
            }
            $row['items'] = $items;

            $query_children = "SELECT * FROM $category_table WHERE parent_id = {$row['id']}";
            $result_children = $this->modx->db->query($query_children);

            $children = array();
            while ($children_row = $this->modx->db->getRow($result_children))
            {
                $children[] = $children_row;
            }
            $row['children'] = $children;

            $categories[] = $row;

            $num_chilren = sizeof($children);

            if ($num_chilren > 0 && $get_children)
            {
                $this->getCategoriesTree($row['id'], $get_children, $path_prefix, $order, $category_table, $categories, $level + 1);
            }
        }

        return $categories;
    }

    function viewAllCategories()
    {
        $table_name = $this->modx->getFullTableName('item_manager_categories');

        $action = $_REQUEST['action'];
        if (!empty($action))
        {
            $category_id = $_REQUEST['category_id'];
            if ($action == 'delete_category' && !empty($category_id) && is_numeric($category_id))
            {
                $this->modx->db->delete($table_name, "id = $category_id");
                $this->removeFile('category', $category_id);
            }
        }

        $all_categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');
        $this->showFilters();
        $categories = $this->paginate($all_categories);

        $this->template_parser->content['table_row.categories'] = '';
        foreach ($categories as $category)
        {
            $path = '';
            if ($category['level'] > 0)
            {
                for ($i = 1; $i < $category['level']; $i++)
                {
                    $path .= "&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                $path .= "|-- ";
            }

            $this->template_parser->content['table_row.categories'] .= "
            <tr>\n
            <td class=\"id\">{$category['id']}</td>\n
            <td class=\"title\">$path<a href=\"{$this->url}&page=edit_category&category_id={$category['id']}\">{$category['name']}</a></td>\n
            <td class=\"parent\">{$category['parent']['name']}</td>\n
            <td class=\"action\">
                <a href=\"{$this->template_parser->content['current_pagination_url']}&action=delete_category&category_id={$category['id']}\" onclick=\"return confirm('{$this->template_parser->content['lang.IM_msg_confirm_deletion']}')\">Delete</a>
            </td>\n
            </tr>\n
            ";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('view_all_categories.tpl', $this->template_parser->content);
    }

    function addNewCategory()
    {
        if (!empty($this->data))
        {
            $errors = array();
            if (empty($this->data['Category']['name']))
            {
                $errors[] = $this->template_parser->content['lang.IM_error_empty_category_name'];
            }

            if (empty($errors))
            {
                $table_name = $this->modx->getFullTableName('item_manager_categories');
                $fields['name'] = $this->data['Category']['name'];
                $fields['title'] = $this->data['Category']['title'];
                $fields['description'] = $this->data['Category']['description'];
                $fields['created'] = $fields['modified'] = date('Y-m-d H:i:s', time());
                $fields['permalink'] = $this->createPermalink($fields['name']);
                if (!empty($this->data['Category']['parent_id']))
                {
                    $fields['parent_id'] = $this->data['Category']['parent_id'];
                }
                else
                {
                    $fields['parent_id'] = 0;
                }

                $category_id = $this->modx->db->insert($fields, $table_name);

                if ($category_id)
                {
                    $allow_types = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
                    $this->handleFileUpload($allow_types, 'category', $category_id);
                    $this->showMessage($this->template_parser->content['lang.IM_msg_add_new_category'], 'successmsg');
                }
            }
            else
            {
                $this->showMessage($errors, 'errormsg');
            }
        }

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\">{$category['name_with_path']}</option>";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('add_new_category.tpl', $this->template_parser->content);
    }

    function editCategory($category_id)
    {
        $action = $_REQUEST['action'];
        if (!empty($action))
        {
            $file_id = $_REQUEST['file_id'];
            if ($action == 'delete_file' && !empty($file_id) && is_numeric($file_id))
            {
                $this->removeFile('category', $category_id, 'delete_one', $file_id);
            }

            if ($action == 'make_primary' && !empty($file_id) && is_numeric($file_id))
            {
                $this->makeFilePrimary('category', $category_id, $file_id);
            }
        }

        if (empty($category_id))
        {
            $this->showMessage($this->template_parser->content['lang.IM_error_category_not_found'], 'errormsg');
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('edit_category.tpl', $this->template_parser->content);
            return;
        }
        $table_name = $this->modx->getFullTableName('item_manager_categories');

        if (empty($this->data))
        {
            $query_category = "SELECT * FROM $table_name WHERE id = $category_id";
            $result_category = $this->modx->db->query($query_category);
            $this->data['Category'] = $this->modx->db->getRow($result_category);
        }
        else
        {
            $errors = array();
            if (empty($this->data['Category']['name']))
            {
                $errors[] = $this->template_parser->content['lang.IM_error_empty_category_name'];
            }

            $query_category = "SELECT * FROM $table_name WHERE id = $category_id";
            $result_category = $this->modx->db->query($query_category);
            $category = $this->modx->db->getRow($result_category);

            if ($this->data['Category']['parent_id'] == $category_id)
            {
                $errors[] = $this->template_parser->content['lang.IM_error_parent_can_not_be_self'];
            }

            if (empty($errors))
            {
                $fields['name'] = $this->data['Category']['name'];
                $fields['title'] = $this->data['Category']['title'];
                $fields['description'] = $this->data['Category']['description'];
                $fields['modified'] = date('Y-m-d H:i:s', time());
                $fields['permalink'] = $this->createPermalink($fields['name']);
                if (!empty($this->data['Category']['parent_id']))
                {
                    $fields['parent_id'] = $this->data['Category']['parent_id'];
                }
                else
                {
                    $fields['parent_id'] = 0;
                }

                $update_success = $this->modx->db->update($fields, $table_name, "id=$category_id");

                if ($update_success)
                {
                    $allow_types = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
                    $this->handleFileUpload($allow_types, 'category', $category_id);
                    $this->showMessage($this->template_parser->content['lang.IM_msg_edit_category'], 'successmsg');
                }
            }
            else
            {
                $this->showMessage($errors, 'errormsg');
            }
        }

        $this->template_parser->content['category.id'] = $this->data['Category']['id'];
        $this->template_parser->content['category.name'] = $this->data['Category']['name'];
        $this->template_parser->content['category.title'] = $this->data['Category']['title'];
        $this->template_parser->content['category.description'] = $this->data['Category']['description'];
        $this->template_parser->content['category.parent_id'] = $this->data['Category']['parent_id'];

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $selected = '';
            if ($this->data['Category']['parent_id'] == $category['id'])
            {
                $selected = ' selected="selected"';
            }
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\"$selected>{$category['name_with_path']}</option>";
        }

        $files = $this->getFiles('category', $category_id);

        $file_count = 1;
        foreach ($files as $file)
        {
            $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=50&height=50&image={$this->modx_base_url}assets/modules/item_manager/uploads/categories/{$category_id}/{$file['file_name']}";
            $edit_url = "{$this->url}&page=edit_category&category_id=$category_id";
            $delete_link = "<a href=\"$edit_url&action=delete_file&file_id={$file['id']}\" onclick=\"return confirm('{$this->template_parser->content['lang.IM_msg_confirm_file_deletion']}')\">Delete</a>";

            $primary_link = "Primary";
            if (!$file['is_primary'])
            {
                $primary_link = "<a href=\"$edit_url&action=make_primary&file_id={$file['id']}\">Make primary</a>";
            }
            $this->template_parser->content['table_row.images'] .= "
            <tr>\n
            <td class=\"col1\">Image $file_count</td>\n
            <td class=\"col2\">\n
                <img src=\"$image_src\" />\n
                 $delete_link | $primary_link\n
            </td>\n
            </tr>\n
            ";
            $file_count++;
        }

        $this->set("file_count", $file_count - 1);

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('edit_category.tpl', $this->template_parser->content);
    }

    function reorderItems($item_type)
    {
        $this->set('item_type', "reorder_$item_type");
        $category_id = $_REQUEST['category_id'];

        if (empty($category_id))
        {
            $category_id = 0;
        }

        if (!empty($_REQUEST['new_orders']) && !empty($_REQUEST['btn_submit']))
        {
            $new_orders = explode(',', $_REQUEST['new_orders']);
            $count = 1;
            foreach ($new_orders as $order)
            {
                $parts =  explode('_', $order);
                $id = $parts[1];
                $table_name = $this->modx->getFullTableName("item_manager_$item_type");

                $query_update_position = "UPDATE $table_name SET position = $count WHERE id = {$id}";
                $this->modx->db->query($query_update_position);
                $count++;
            }
            $this->showMessage($this->template_parser->content['lang.IM_msg_position_updated'], 'successmsg');
        }

        $items = array();

        $this->set('category.id', $category_id);

        if ($item_type == 'items')
        {
            $items = $this->getAllItems($category_id, "ORDER BY position ASC");
        }
        else if ($item_type == 'categories')
        {
            $items = $this->getCategoriesTree($category_id, false, null, "ORDER BY position ASC");
        }

        $this->set('view.products', '');
        $this->append('view.products', "<ul id=\"sortable\">\n");

        $count = 1;
        foreach ($items as $item)
        {
            $image_src = "";

            if (!empty($item['files']))
            {
                $primary_file_index = $this->getPrimaryFileIndex($item['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=25&height=25&cropratio=1:1&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
            }

            $this->append('view.products', "<li id=\"item_{$item['id']}\" class=\"ui-state-default\"><span style=\"z-index:999;\" class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span> <span class=\"order_thumb\" style=\"margin:0 1px;\"><img src=\"$image_src\" /></span> <span style=\"margin:2px 0 0 40px;\">{$item['name']}</span></li>");
            $count++;
        }
        $this->append('view.products', "</ul>\n");

        $categories = $this->getCategoriesTree(null, true, '|-- ', 'ORDER BY position ASC');

        foreach ($categories as $category)
        {
            $selected = '';
            if ($category_id == $category['id'])
            {
                $selected = ' selected="selected"';
            }
            $this->template_parser->content['select.categories'] .= "<option value=\"{$category['id']}\"$selected>{$category['name_with_path']}</option>";
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('reorder_items.tpl', $this->template_parser->content);
    }

    function templates()
    {
        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('templates.tpl', $this->template_parser->content);
    }

    function config()
    {
        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('config.tpl', $this->template_parser->content);
    }

    function generateItemsSubNav($root_id, $hide = false)
    {
        $current_category_id = $_REQUEST['pcat'] ? $_REQUEST['pcat'] : 0;
        $parent = $this->getCategoryParent($current_category_id);

        $display = $hide ? "class=\"hide\"" : "class=\"show\"";
        foreach ($parent as $category)
        {
            if ($category['id'] == $root_id)
            {
                $display = "class=\"show\"";
            }
        }

        $categories = $this->getCategoriesTree($root_id, false, null, "ORDER BY position ASC");
        $content = "<ul $display id=\"ul_subnav_$root_id\">\n";
        foreach ($categories as $category)
        {
            $content .= "<li>";

            if (!empty($category['children']))
            {
                $content .= "<a href=\"javascript:\" onclick=\"$('#ul_subnav_{$category['id']}').toggle('fast');\">{$category['name']}</a>";
                $content .= $this->generateItemsSubNav($category['id'], true);
            }
            else
            {
                $url = $this->modx_base_url . "index.php?id={$_REQUEST['id']}&pcat={$category['id']}&pip=9";
                $content .= "<a href=\"$url\">{$category['name']}</a>";
            }

            $content .= "</li>";
        }
        $content .= "</ul>\n";
        return $content;
    }

    function showRanaDetailProduct($product_id)
    {
        $this->genereateRanaBreadcrumb('rana');
        $items = $this->getAllItems();
        $item = null;
        $prev_item = null;
        $next_item = null;
        //foreach ($items as $result_item)
        for ($i = 0; $i < sizeof($items); $i++)
        {
            if ($items[$i]['id'] == $product_id)
            {
                $item = $items[$i];

                $prev_item = $items[$i - 1 >= 0 ? $i - 1 : sizeof($items) - 1];
                $next_item = $items[$i + 1 < sizeof($items) ? $i + 1 : 0];

                break;
            }
        }
        $this->set('product.name', $item['name']);
        $this->set('product.price', $item['price'] ? "<span class=\"price\">\${$item['price']}</span>" : "");
        $this->set('product.description', $item['description']);

        $table_name = $this->modx->getFullTableName('item_manager_items');
        $hits = $item['hits'] + 1;
        $query_update_views_count = "UPDATE $table_name SET hits = $hits WHERE id = {$product_id}";
        $this->modx->db->query($query_update_views_count);

        $file_count = 0;
        $files_count = sizeof($item['files']);
        $this->set('product.files_count', $files_count);

        $this->append('product.files.views', "<div class=\"photo-nav\" style=\"display: block; position: relative; float: right;\">Alternate views: ");
        $primary_index = !empty($_REQUEST['primary_index']) ? $_REQUEST['primary_index'] - 1 : $this->getPrimaryFileIndex($item['files']);
        $this->set('product.primary_file_index', $primary_index);

        foreach ($item['files'] as $file)
        {
            $display = " hide";

            $image_big_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=960&height=1440&cropratio=2:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$file_count]['file_name']}";
            $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=320&height=480&cropratio=2:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$file_count]['file_name']}";

            $display_count = $file_count + 1;
            if ($primary_index == $file_count)
            {
                $this->append('product.files.views', "<span class=\"current\">$display_count</span>");
                $this->append('product.files', "<div id=\"photo_$file_count\" class=\"photo\"><a class=\"jqzoom\" href=\"$image_big_src\"><img src=\"$image_src\" alt=\"{$item['name']}\" /></a></div>\n");
            }
            else
            {
                $link = $this->template_parser->content['current_pagination_url'] . "&iid={$item['id']}&primary_index={$display_count}";
                $this->append('product.files.views', "<a href=\"$link\">$display_count</a>");
            }

            if ($file_count < $files_count - 1)
            {
                $this->append('product.files.views', ' | ');
            }

            $file_count++;
        }

        $this->append('product.files.views', "</div>");

        $prev_link = $this->template_parser->content['current_pagination_url'] . "&iid={$prev_item['id']}";
        $next_link = $this->template_parser->content['current_pagination_url'] . "&iid={$next_item['id']}";
        $this->append('product.files.items_nav', "<p><a href=\"$prev_link\">Previous</a> | <a href=\"$next_link\">Next</a></p>");

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('rana_product_detail.tpl', $this->template_parser->content);
    }

    function showRanaProductsListing()
    {
        $all_items = $this->getAllItems(null, "ORDER BY position ASC");
        $items = $this->paginate($all_items, 'rana');

        $content = "";
        foreach ($items as $item)
        {
            $primary_file_index = $this->getPrimaryFileIndex($item['files']);
            $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=230&height=345&cropratio=2:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
            $link = $this->template_parser->content['current_pagination_url'] . "&iid={$item['id']}";
            $content .= "
            <div class=\"aProduct\">
                <p class=\"photo\"><a href=\"$link\"><img src=\"$image_src\" alt=\"{$item['name']}\" /></a></p>
                <p class=\"text\"><a href=\"$link\">{$item['name']}</a></p>
            </div>
            ";
        }

        $this->template_parser->content['rana.products'] .= $content;
    }

    function showRanaProductsLookbook()
    {
        $items = $this->getAllItems($this->root_id, "ORDER BY position ASC");

        $content = "";
        foreach ($items as $item)
        {
            $primary_file_index = $this->getPrimaryFileIndex($item['files']);
            $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=320&height=480&cropratio=2:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
            $link = $this->template_parser->content['current_pagination_url'] . "&iid={$item['id']}";
            $content .= "<li><img src=\"$image_src\" alt=\"{$item['name']}\" /></li>\n";
        }
        $this->template_parser->content['rana.products'] .= $content;
    }

    function showRanaProductsSubNav()
    {
        $this->template_parser->content['rana.subnav'] = "<div id=\"subnav\">\n";
        $this->template_parser->content['rana.subnav'] .= $this->generateItemsSubNav($this->root_id);
        $this->template_parser->content['rana.subnav'] .= "</div>\n";
    }

    function showRanaProducts()
    {
        switch ($this->template)
        {
            case 'lookbook':
                $this->showRanaProductsLookbook();
                $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('rana_products_lookbook.tpl', $this->template_parser->content);
                break;
            default:
                $this->showRanaProductsSubNav();
                $this->showRanaProductsListing();
                $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('rana_products.tpl', $this->template_parser->content);
        }
    }

    function showSEOIIVGallery()
    {
        $root_id = empty($_REQUEST['root_id']) ? $this->root_id : $_REQUEST['root_id'];
        $type = empty($_REQUEST['type']) ? 'cat' : $_REQUEST['type'];
        $this->template_parser->content['view.gallery_type'] = $type;
        //$this->template_parser->content['view.header_title'] = 'Gallery';

        if (!empty($root_id) && is_numeric($root_id) && $root_id > 0)
        {

        }
        else
        {
            $root_id = 0;
        }

        if ($type == 'cat')
        {
            $categories = $this->getCategoriesTree($root_id, false);

            if (!empty($categories[0]['parent']['name']))
            {
                $this->template_parser->content['view.header_title'] = $categories[0]['parent']['name'];
            }
            else
            {
                $this->template_parser->content['view.header_title'] = 'Gallery';
            }

            foreach ($categories as $category)
            {
                $primary_file_index = $this->getPrimaryFileIndex($item['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=200&height=150&cropratio=4:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/categories/{$category['id']}/{$category['files'][$primary_file_index]['file_name']}";
                $link = 'javascript:';
                if (count($category['children']) > 0)
                {
                    $link = "index.php?id={$_REQUEST['id']}&root_id={$category['id']}&type=cat";
                }
                else
                {
                    $link = "index.php?id={$_REQUEST['id']}&root_id={$category['id']}&type=img";
                }

                $this->template_parser->content['view.gallery'] .= "<div class=\"aCat\">\n
                    <div class=\"pic\"><a href=\"$link\"><img src=\"$image_src\" alt=\"img\" width=\"200\" height=\"150\" /></a></div>\n
                    <div class=\"info\"><a href=\"$link\">{$category['name']}</a></div>\n
                </div>\n";




            }
            $this->genereateBreadcrumb();
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('seoiiv_gallery_list.tpl', $this->template_parser->content);
        }
        elseif ($type == 'img')
        {
            $items = $this->getAllItems($root_id);

            if (!empty($items[0]['category']['name']))
            {
                $this->template_parser->content['view.header_title'] = $items[0]['category']['name'];
            }
            else
            {
                $this->template_parser->content['view.header_title'] = 'Gallery';
            }

            $count = 1;
            foreach($items as $item)
            {
                $primary_file_index = $this->getPrimaryFileIndex($item['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=200&height=150&cropratio=4:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
                $link = "index.php?id={$_REQUEST['id']}&root_id={$item['category_id']}&type=view_album&selected=$count";
                $this->template_parser->content['view.gallery'] .= "<div class=\"anImg\">\n
                    <div class=\"pic\"><a href=\"$link\"><img src=\"$image_src\" alt=\"img\" width=\"200\" height=\"150\" /></a></div>\n
                    <div class=\"info\">{$item['name']}</div>\n
                </div>\n";
                $count++;
            }
            $this->genereateBreadcrumb();
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('seoiiv_gallery_list.tpl', $this->template_parser->content);
        }
        elseif ($type == 'view_album')
        {
            $items = $this->getAllItems($root_id);
            $this->template_parser->content['image.selected'] = empty($_REQUEST['selected']) ? 1 : $_REQUEST['selected'];

            $items_count = sizeof($items);
            $this->template_parser->content['image.count'] = $items_count;

            if ($items_count > 1)
            {
                $this->template_parser->content['image.nav'] = "<a id=\"prev\" href=\"javascript:\">Prev</a> | <a id=\"next\" href=\"javascript:\">Next</a>";
            }
            else
            {
                $this->template_parser->content['image.nav'] = "Prev | Next";
            }

            $count = 1;
            foreach ($items as $item)
            {
                $primary_file_index = $this->getPrimaryFileIndex($item['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=600&height=400&cropratio=3:2&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
                $this->template_parser->content['view.gallery'] .= "<img id=\"gallery-image-$count\" src=\"$image_src\" name=\"{$item['name']}\" alt=\"img\" width=\"600\" height=\"400\" />\n";
                $count++;
            }
            $this->genereateBreadcrumb();
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('seoiiv_gallery_detail.tpl', $this->template_parser->content);
        }

    }

    function showPatinaProducts()
    {
        $roomset_id = $_REQUEST['roomset_id'];
        $collection_id = $_REQUEST['collection_id'];
        $furniture_type_id = $_REQUEST['furniture_type_id'];

        if (!$furniture_type_id)
        {
            $categories_items_table_name = $this->modx->getFullTableName('item_manager_categories_items');
            $query_categories_items = "SELECT DISTINCT item_id FROM $categories_items_table_name WHERE category_id IN ($filter_category)";
        }
        else
        {
            
        }

        $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('patina_products.tpl', $this->template_parser->content);
    }
    
    function showPatinaRoomset($roomset_id)
    {
        $roomset = $this->getCategory($roomset_id);
        if (!empty($roomset))
        {
            $collection_parent = $this->getCategoryByName('Collection');
            $collections = $this->getCategoriesTree($collection_parent['id']);
            $this->debug($collections);

            $change_links = "";
            $links_list = "";
            $count = 0;
            $collections_count = sizeof($collections);
            foreach ($collections as $collection)
            {
                $image_file_name = $roomset['name'] . ' ' . $collection['name'];
                $image_file_name = strtolower(str_replace(' ', '_', $image_file_name)) . '.jpeg';
                $this->debug($image_file_name);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=600&height=360&cropratio=5:3&image={$this->modx_base_url}assets/modules/item_manager/uploads/categories/$image_file_name";
                $link = "index.php?id={$_REQUEST['id']}&roomset_id=$roomset_id&collection_id={$collection['id']}";
                $this->template_parser->content['roomset.list'] .= "
                    <div id=\"collection-photo-$count\"><a href=\"$link\" title=\"View {$collection['name']} collection\"><img src=\"$image_src\" /></a></div>
                ";
                $link_separator = ' | ';
                if ($count == $collections_count - 1)
                {
                    $link_separator = '';
                }
                $change_links .= "<a id=\"collection-link-$count\" href=\"javascript:\" onclick=\"change_collection($count)\">{$collection['name']}</a>" . $link_separator;
                $links_list .= "<a id=\"collection-more-link-$count\" class=\"more\" href=\"$link\">View collection</a>";
                $count++;
            }

            $this->set('roomset.links', $links_list);
            
            $this->template_parser->content['roomset.list'] .= "
                <div id=\"collection-nav\">$change_links</div>
                <script type=\"text/javascript\">
                    var collections_count = $collections_count;
                    function change_collection(collection_id)
                    {
                        for (i = 0; i < collections_count; i++)
                        {
                            $('#collection-photo-' + i).hide();
                            $('#collection-more-link-' + i).hide();
                            $('#collection-link-' + i).attr('style', 'text-decoration: underline;');
                        }
                        $('#collection-photo-' + collection_id).show();
                        $('#collection-more-link-' + collection_id).show();
                        $('#collection-link-' + collection_id).attr('style', 'text-decoration: none;');
                        $('#collection-span').html($('#collection-link-' + collection_id).html());
                        
                    }
                    $(document).ready(function(){
                        change_collection(0);
                    })
                    
                </script>
            ";

            $this->set('roomset.name', $roomset['name']);
            $this->set('roomset.title', $roomset['title']);
            $this->set('roomset.description', $roomset['description']);
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('patina_roomset.tpl', $this->template_parser->content);
        }
        
    }

    function showTTGallery($category_id)
    {
        $this->checkAccess();
        if (!empty($_SESSION['login']['username']))
        {
            $category = $this->getCategory($category_id);
            $this->set('ttgallery.name', $category['name']);
            $all_items = $this->getAllItems($category_id, "ORDER BY position ASC");
            $items = $this->paginate($all_items, 'ttgallery', 24);
            $this->set('ttgallery.pictures', '');
            $items_count = sizeof($items);
            $item_index = 0;
            foreach ($items as $item)
            {
                $primary_file_index = $this->getPrimaryFileIndex($item['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=128&height=128&cropratio=1:1&image={$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
                $image_src_big = "{$this->modx_base_url}assets/modules/item_manager/uploads/items/{$item['id']}/{$item['files'][$primary_file_index]['file_name']}";
                $this->append('ttgallery.pictures', "
                    <div class=\"picture\">
                        <div class=\"number\">" . ($item_index + 1) . "</div>
                        <div class=\"photo\"><a href=\"$image_src_big\" rel=\"lightbox-gallery\"><img src=\"$image_src\" width=\"128\" height=\"88\" alt=\"\" /></a></div>
                    </div>
                ");
                $item_index++;
            }
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('ttgallery_show.tpl', $this->template_parser->content);
        }
        else
        {
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('ttgallery_login.tpl', $this->template_parser->content);
        }
    }

    function showTTGalleryHome()
    {
        $this->checkAccess();
        if (!empty($_SESSION['login']['username']))
        {
            $categories = $this->getCategoriesTree();
            $this->set('ttgallery.categories', '');
            $categories_count = sizeof($categories);
            $category_index = 0;
            foreach ($categories as $category)
            {
                $right = "";
                if ($category_index % 2 != 0)
                {
                    $right = " right";
                }
                $primary_file_index = $this->getPrimaryFileIndex($category['files']);
                $image_src = "{$this->modx_base_url}assets/modules/item_manager/images/image.php?image.jpeg?width=468&height=348&cropratio=468:348&image={$this->modx_base_url}assets/modules/item_manager/uploads/categories/{$category['id']}/{$category['files'][$primary_file_index]['file_name']}";
                $link = "index.php?id={$_REQUEST['id']}&gallery_id={$category['id']}";
                $this->append('ttgallery.categories', "
                    <div class=\"category$right\">
                        <div class=\"photo\">
                            <a href=\"$link\" title=\"View pictures\">
                                <img src=\"$image_src\" alt=\"{$category['name']}\" width=\"468\" height=\"348\" />
                            </a>
                        </div>
                        <div class=\"title\">
                            <a href=\"$link\">{$category['name']}</a>
                        </div>
                    </div>
                ");
                $category_index++;
            }
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('ttgallery_home.tpl', $this->template_parser->content);
        }
        else
        {
            $this->template_parser->content['view.content'] = $this->template_parser->parseTemplate('ttgallery_login.tpl', $this->template_parser->content);
        }
    }
}

?>
